package com.ybb.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import com.ybb.order_enum.Operator;
import com.ybb.pojo.Role;
import com.ybb.pojo.User;
import com.ybb.service.RoleService;
import com.ybb.service.RoleServiceImpl;
import com.ybb.service.UserService;
import com.ybb.service.UserServiceImpl;
import jdk.nashorn.internal.ir.CallNode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/jsp/user.do")
public class UserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    RoleService roleService = new RoleServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (Operator.PWDMODIFY.getOperator().equals(method)) {
            pwdModify(req, resp);
        } else if (Operator.QUERY.getOperator().equals(method)) {
            getAllUsers(req, resp);
        } else if (Operator.VIEW.getOperator().equals(method)) {
            getUserByUid(req, resp);
        } else if (Operator.MODIFY.getOperator().equals(method)) {
            modifyUser(req, resp);
        } else if (Operator.GETROLELIST.getOperator().equals(method)) {
            getRoleList(req, resp);
        } else if (Operator.DELUSER.getOperator().equals(method)) {
            deleteUser(req, resp);
        } else if (Operator.USERCODEEXIST.getOperator().equals(method)) {
            userCodeExists(req, resp);
        }

    }

    private void userCodeExists(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        boolean hasUserCode = userService.hasUserCode(userCode);
        Map<String, String> map = new HashMap<String, String>();
        if (hasUserCode) {
            map.put("userCode", "exist");
        } else {
            map.put("userCode", "notExist");
        }

        resp.setContentType("application/json");
        JSONArray.toJSONString(map);
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                writer.close();
            }
        }


    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        Map<String, String> map = new HashMap<String, String>();
        boolean exists = userService.isExists(Long.valueOf(uid));
        if (!exists) {
            map.put("delResult", "notExist");
        } else {

            int deleteRows = userService.deleteUser(Long.valueOf(uid));

            if (deleteRows > 0) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }
        resp.setContentType("application/json");
        String jsonString = JSONArray.toJSONString(map);
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }


    }

    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
        List<Role> roleList = roleService.getAllRole();

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Role role : roleList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", role.getId());
            map.put("roleName", role.getRoleName());
            list.add(map);
        }

        PrintWriter writer = null;
        try {
            resp.setContentType("application/json");
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(list));
            writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    private void modifyUser(HttpServletRequest req, HttpServletResponse resp) {
        String userId = req.getParameter("uid");
        User user = userService.getUserById(Long.valueOf(userId));
        req.getSession().setAttribute("user", user);
        try {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void getUserByUid(HttpServletRequest req, HttpServletResponse resp) {
        String userId = req.getParameter("uid");
        User user = userService.getUserById(Long.valueOf(userId));
        req.getSession().setAttribute("user", user);
        try {
            req.getRequestDispatcher("userview.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void getAllUsers(HttpServletRequest req, HttpServletResponse resp) {

        HttpSession session = req.getSession();
        List<Role> roleList = roleService.getAllRole();
        session.setAttribute("roleList", roleList);


        String queryName = req.getParameter("queryName");
        String queryUserRole = req.getParameter("queryUserRole");
        session.setAttribute("queryUserName", queryName);


        int userCountPerPage = 5;


        //获取当前页数并设置作用域
        String currentPageNo = req.getParameter("pageIndex");
        int currentPageNum = 1;

        if (!StringUtils.isNullOrEmpty(currentPageNo)) {// NULL ""
            currentPageNum = Integer.valueOf(currentPageNo);

        }


        session.setAttribute("userCountPerPage", userCountPerPage);
        session.setAttribute("currentPageNo", currentPageNum);


        /*
        获取总页数
        获取用户数量
        获取当前页
         */
        long userRole = 0;


        if (!StringUtils.isNullOrEmpty(queryUserRole)) {
            userRole = Long.valueOf(queryUserRole);
            session.setAttribute("queryUserRole", queryUserRole);
        }

        int usersCount = userService.getUsersCount(queryName, userRole);


        //用户总量
        session.setAttribute("totalCount", usersCount);


        //获取总页数
        int totalPageCount = usersCount / userCountPerPage;
        if (usersCount % userCountPerPage != 0) {
            totalPageCount += 1;
        }
        session.setAttribute("totalPageCount", totalPageCount);


        List<User> users = userService.getUsers(queryName, userRole, currentPageNum, userCountPerPage);

        session.setAttribute("userList", users);
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (Operator.SAVEPWD.getOperator().equals(method)) {
            savePassword(req, resp);
        } else if (Operator.MODIFYEXE.getOperator().equals(method)) {
            userModify(req, resp);

        }else if(Operator.ADD.getOperator().equals(method)){
            addUser(req,resp);
        }

    }

    private void addUser(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user=new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            user.setBirthday(simpleDateFormat.parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Long.valueOf(userRole));

        User userSession = (User) req.getSession().getAttribute("userSession");
        user.setCreateBy(userSession.getId());
        user.setCreationDate(new Date());

        int insertRows = userService.insertUser(user);
        if(insertRows>0){
            try {
                req.getRequestDispatcher("insert-success.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            req.getSession().setAttribute("insertFailed","插入用户信息失败");
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void userModify(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        String uid = req.getParameter("uid");


        User user = new User();
        user.setId(Long.valueOf(uid));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            user.setBirthday(simpleDateFormat.parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Long.valueOf(userRole));

        int upDateRows = userService.upDateUser(user);
        if (upDateRows > 0) {
            try {
                req.getRequestDispatcher("user_modify_success.jsp").forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            req.getSession().setAttribute("updateUserFailed", "修改用户信息失败");
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void savePassword(HttpServletRequest req, HttpServletResponse resp) {
        //更新密码
        String oldPassword = req.getParameter("oldpassword");
        String newPassword = req.getParameter("newpassword");
        String rNewPassword = req.getParameter("rnewpassword");
        User userSession = (User) req.getSession().getAttribute("userSession");


        if (newPassword.equals(rNewPassword)) {
            if (userSession != null) {
                Long id = userSession.getId();
                int effectRows = userService.updatePassword(id, oldPassword, newPassword);
                if (effectRows > 0) {
                    try {
                        req.getRequestDispatcher("pwd-success.jsp").forward(req, resp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    req.getSession().setAttribute("message", "修改密码失败");
                    try {
                        resp.sendRedirect(req.getContextPath() + "/jsp/pwdmodify.jsp");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                try {
                    resp.sendRedirect(req.getContextPath() + "/login.jsp");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            req.getSession().setAttribute("message", "两次密码不一致");
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/pwdmodify.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
        String oldPassword = req.getParameter("oldPassword");
        User user = (User) req.getSession().getAttribute("userSession");
        Map<String, String> map = new HashMap<String, String>();
        if (user == null) {
            //要么没登录，要么登录失效，需要重新登录
            map.put("result", "sessionInvalid");

        } else {

            if (user.getUserPassword().equals(oldPassword)) {
                map.put("result", "true");

            } else if (StringUtils.isNullOrEmpty(oldPassword)) {
                map.put("result", "empty");
            } else {
                map.put("result", "false");
            }

        }
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }

    }
}
